import { Request, Response } from 'express';
import orderService from '../../services/order.service';

export class Controller {
    // 创建订单
    create(req: Request, res: Response): void {
        // 解析出参数和用户id
        let address = req.body.address
        let uid = (req.headers as any).user.id
        orderService.create(address, uid).then(()=>{
            res.status(200).json({ msg: 'ok' })
        }).catch((error)=>{
            res.status(200).json({ msg: 'error', error: error })
        })
    }
    // 获取订单列表
    get(req: Request, res: Response): void {
        // 解析参数
        let role = (req.headers as any).user.role
        let type = Number(req.query.type as string)
        // 非管理员不允许获取所有订单数据
        if (type == 0 && role != 'admin') {
            res.status(200).json({ msg: 'error', error: '无操作权限' })
            return
        }
        let uid = undefined // 用户id
        if (type == 1) {
            uid = (req.headers as any).user.id
        }
        let offset = Number(req.query.offset as string) // 分页位置
        let limit = Number(req.query.limit as string)   // 分页条数
        let order = req.query.order as string           // 排序规则
        let filter:number | undefined = Number(req.query.filter as string) // 筛选
        if (Number.isNaN(filter)) {
            filter = undefined
        }
        orderService.query(offset, limit, uid, order, filter).then((data)=>{
            res.status(200).json({ msg: 'ok', datas: data })
        }).catch((error)=>{
            res.status(200).json({ msg: 'error', error: error })
        })
    }
    // 更新订单状态
    update(req: Request, res: Response): void {
        let state = Number(req.query.state as string)   // 目标状态
        let oid = Number(req.query.oid as string)       // 订单id
        if (!state || !oid) {
            res.status(200).json({ msg: 'error', error: '数据异常' })
            return
        }
        let role = (req.headers as any).user.role
        // 已完成状态只允许服务端进行更新
        if (state >= 3) {
            res.status(200).json({ msg: 'error', error: '无操作权限' })
            return
        // 已发货状态只允许管理员用户进行操作
        } else if (state == 1 && role != 'admin') {
            res.status(200).json({ msg: 'error', error: '无操作权限' })
            return
        } else {
            orderService.update(oid, state).then(()=>{
                res.status(200).json({ msg: 'ok' })
            }).catch((error)=>{
                res.status(200).json({ msg: 'error', error: error })
            })
        }
    }
}
export default new Controller();